﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace GrainManage.Web.Common
{
    public class RSAEncrypt
    {
        public static string Decrypt(string base64code, string privateKey)
        {
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(privateKey);
                byte[] encryptedData = Convert.FromBase64String(base64code);
                byte[] decryptedData = RSA.Decrypt(encryptedData, false);
                string utf8code = Encoding.UTF8.GetString(decryptedData);
                return utf8code;
            }
        }

        public static string Decrypt(string base64code, byte[] privateKey)
        {
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.ImportCspBlob(privateKey);
                byte[] encryptedData = Convert.FromBase64String(base64code);
                byte[] decryptedData = RSA.Decrypt(encryptedData, false);
                string utf8code = Encoding.UTF8.GetString(decryptedData);
                return utf8code;
            }
        }

        public static string Encrypt(string stringToEncrypt, string publicKey)
        {
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.FromXmlString(publicKey);
                byte[] dataToEncrypt = Encoding.UTF8.GetBytes(stringToEncrypt);
                byte[] encryptedData = RSA.Encrypt(dataToEncrypt, false);
                string base64code = Convert.ToBase64String(encryptedData);
                return base64code;
            }
        }

        public static string Encrypt(string stringToEncrypt, byte[] publicKey)
        {
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.ImportCspBlob(publicKey);
                byte[] dataToEncrypt = Encoding.UTF8.GetBytes(stringToEncrypt);
                byte[] encryptedData = RSA.Encrypt(dataToEncrypt, false);
                string base64code = Convert.ToBase64String(encryptedData);
                return base64code;
            }
        }
    }
}
